package com.cloudeasy.user.service.expand;

import com.cloudeasy.api.constant.AmqpConstant;
import com.cloudeasy.api.util.JsonUtil;
import com.cloudeasy.api.vo.amqp.AuthCodeVO;
import com.cloudeasy.api.vo.Result;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.stereotype.Service;

@Service
public class EmailService {
    private final AuthCodeService authCodeService;

    private final AmqpTemplate amqpTemplate;

    public EmailService(AuthCodeService authCodeService, AmqpTemplate amqpTemplate) {
        this.authCodeService = authCodeService;
        this.amqpTemplate = amqpTemplate;
    }

    /**
     * 发送邮件验证码
     *
     * @param email 接受邮箱
     * @return {@link Boolean}
     */
    public Boolean sendAuthCode(String email) {
        String authCode = RandomStringUtils.randomNumeric(6);
        // 备份保存在redis中，过期时间5分钟
        authCodeService.save(email, authCode);
        // 发送给消息中间件处理
        AuthCodeVO authCodeVO = AuthCodeVO.builder()
                .recipient(email)
                .authCode(authCode)
                .build();
        amqpTemplate.convertAndSend(AmqpConstant.SmtpConstant.ROUTING_KEY, JsonUtil.toJson(authCodeVO));
        return true;
    }
}
